package com.system.borrow.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.R;
import com.system.borrow.bean.CustomerDTO;
import com.system.borrow.bean.GloData;
import com.system.borrow.cache.CacheMode;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.http.model.HttpParams;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.ChooseCity;
import com.system.borrow.utils.ChooseCityInterface;
import com.system.borrow.utils.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * ================================================
 * 作    者：LuCenly(落尘)
 * 版    本：1.0
 * 创建日期：2016/12/1 17:08
 * 描    述：个人信息
 * ================================================
 */
public class UserFragment extends Fragment implements View.OnClickListener {
    View myView;
    Spinner spinner_sr, spinner_city, spinner_xyk;
    //    String[] sr = new String[]{"请选择", "1000", "2000", "3000", "5000", "1万-2万", "5万以上"};
    String[] citys = new String[]{"请选择", "未婚", "已婚"};
    String[] xyks = new String[]{"请选择", "高中", "大专", "本科", "硕士", "博士"};
    int marriage = 0, edcation = 0, cityid = 0;
    private EditText et_name, et_mobile, et_id_card;
    private Button btn_save;
    private TextView tv_city;
    String[] oldCityArray = new String[]{"北京市","北京市"};
    String[] oldCodeArray = new String[]{"1", "1"};

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (myView == null) {
            myView = inflater.inflate(R.layout.fragment_user, container, false);
        } else {
            ViewParent parent = myView.getParent();
            if (parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(myView);
            }
        }
        initView(myView);
        addAction();
        return myView;
    }

    private void addAction() {
        btn_save.setOnClickListener(this);
//        //将可选内容与ArrayAdapter连接起来
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, sr);
//
//        //设置下拉列表的风格
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//
//        //将adapter 添加到spinner中
//        spinner_sr.setAdapter(adapter);
        //将可选内容与ArrayAdapter连接起来
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, citys);

        //设置下拉列表的风格
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter 添加到spinner中
        spinner_city.setAdapter(adapter2);
        spinner_city.setSelection((int) GloData.getCustomerDTO().isMarriage(), true);
        spinner_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                marriage = position;
                GloData.getCustomerDTO().setMarriage(marriage);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //将可选内容与ArrayAdapter连接起来
        ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, xyks);

        //设置下拉列表的风格
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter 添加到spinner中
        spinner_xyk.setAdapter(adapter3);
        spinner_xyk.setSelection((int) GloData.getCustomerDTO().getEdcation(), true);
        spinner_xyk.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                edcation = position;
                GloData.getCustomerDTO().setEdcation(edcation);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        et_mobile.setText(GloData.getCustomerDTO().getMobile() + "");
        if (GloData.getCustomerDTO().getSelfCard().length() > 0) {
            et_id_card.setText(GloData.getCustomerDTO().getSelfCard() + "");
        }
        if (GloData.getCustomerDTO().getName().length() > 0) {
            et_name.setText(GloData.getCustomerDTO().getName());
        }
        if (GloData.getCustomerDTO().getCityId() != 0) {
            for (int i = 0; i < GloData.getList().size(); i++) {
                for (int j = 0; j < GloData.getList().get(i).child.size(); j++) {
                    if (GloData.getList().get(i).child.get(j).value.equals(GloData.getCustomerDTO().getCityId() + "")) {
                        Log.v("code1",GloData.getList().get(i).child.get(j).value+"==========");
                        tv_city.setText(GloData.getList().get(i).name + GloData.getList().get(i).child.get(j).name);
                        oldCityArray = new String[]{GloData.getList().get(i).name, GloData.getList().get(i).child.get(j).name};
                    }
                }
            }
        }
    }

    private void initView(View myView) {
//        spinner_sr = (Spinner) myView.findViewById(R.id.spinner_sr);
        spinner_city = (Spinner) myView.findViewById(R.id.spinner_city);
        spinner_xyk = (Spinner) myView.findViewById(R.id.spinner_xyk);
        et_name = (EditText) myView.findViewById(R.id.et_name);
        et_mobile = (EditText) myView.findViewById(R.id.et_mobile);
        et_id_card = (EditText) myView.findViewById(R.id.et_id_card);
        btn_save = (Button) myView.findViewById(R.id.btn_save);
        tv_city = (TextView) myView.findViewById(R.id.tv_city);
        tv_city.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save://int marriage = 0, edcation = 0, cityid = 0;
                String name = et_name.getText().toString();
                GloData.getCustomerDTO().setName(name);
                String mobile = et_mobile.getText().toString().trim();
                GloData.getCustomerDTO().setMobile(mobile);
                String ID_card = et_id_card.getText().toString().trim();
                GloData.getCustomerDTO().setSelfCard(ID_card);
                if (GloData.getCustomerDTO().getName() == null || GloData.getCustomerDTO().getName().isEmpty()) {
                    Toast.makeText(getActivity(), "请输入姓名", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (name == null) {
                        name = GloData.getCustomerDTO().getName();
                    }
                }
                if (GloData.getCustomerDTO().getMobile() == null|| GloData.getCustomerDTO().getMobile().isEmpty()) {
                    Toast.makeText(getActivity(), "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (mobile == null) {
                        mobile = GloData.getCustomerDTO().getMobile();
                    }
                }
                if (GloData.getCustomerDTO().getSelfCard() == null || GloData.getCustomerDTO().getSelfCard().isEmpty()) {
                    Toast.makeText(getActivity(), "请输入身份证号码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (ID_card == null) {
                        ID_card = GloData.getCustomerDTO().getSelfCard();
                    }
                }
                if (GloData.getCustomerDTO().getCityId() == 0) {
                    Toast.makeText(getActivity(), "请选择城市", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (cityid == 0) {
                        cityid = (int) GloData.getCustomerDTO().getCityId();
                    }
                }
                if (GloData.getCustomerDTO().isMarriage() == 0) {
                    Toast.makeText(getActivity(), "请选择婚姻状况", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (marriage == 0) {
                        marriage = (int) GloData.getCustomerDTO().isMarriage();
                    }
                }
                if (GloData.getCustomerDTO().getEdcation() == 0) {
                    Toast.makeText(getActivity(), "请选择文化程度", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (edcation == 0) {
                        edcation = (int) GloData.getCustomerDTO().getEdcation();
                    }
                }
                saveData(name, mobile, ID_card, marriage, edcation);
                break;
            case R.id.tv_city:
                final ChooseCity chooseCity = new ChooseCity();
                chooseCity.createDialog(getActivity(), oldCityArray, oldCodeArray,new ChooseCityInterface() {
                    @Override
                    public void sure(String[] newCityArray, String[] newCodeArray) {
                        Log.v("code",Long.parseLong(newCodeArray[1])+"==========");
                        GloData.getCustomerDTO().setCityId(Long.parseLong(newCodeArray[1]));
                        tv_city.setText(newCityArray[0] + newCityArray[1]);
                        oldCityArray = new String[]{newCityArray[0], newCityArray[1]};
                    }
                });
                break;
        }
    }

    /**
     * @param name
     * @param mobile
     * @param id_card
     * @param marriage
     * @param edcation
     */
    private void saveData(String name, String mobile, String id_card, long marriage, long edcation) {
        HttpParams params = new HttpParams();
        params.put("name", name);
        params.put("mobile", mobile);
        params.put("selfCard", id_card);
        params.put("cityId", cityid + "");
        params.put("marriage", marriage + "");
        params.put("edcation", edcation + "");
        OkHttpUtils.post(URLDefind.EDIT)
                .tag(this)
                .params(params)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new DialogCallback<String>(getActivity(), String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int statusCode = jsonObject.getInt("statusCode");
                            Gson gson = new Gson();
                            if (statusCode == 200) {
                                String data = jsonObject.getString("data");
                                TypeToken<CustomerDTO> token = new TypeToken<CustomerDTO>() {
                                };
                                CustomerDTO customer = gson.fromJson(data, token.getType());
                                GloData.setCustomerDTO(customer);
                                SharedPreferencesUtil.putString(getActivity(), "custormer", "custormer", gson.toJson(customer));
                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }
}
